package com.lance.answer.gui.answer.gk.answer.lms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.AnswerObject;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.dto.CourseInfo;
import com.lance.answer.gui.answer.gk.answer.lms.dto.LmsExamInfo;
import com.lance.answer.gui.answer.gk.answer.lms.export.ExportLmsExamInfo;
import com.lance.answer.gui.answer.gk.answer.lms.util.AnalysisIdentifyingCode;
import com.lance.answer.gui.answer.gk.answer.lms.util.ImageUtil;
import com.lance.answer.question_answer.T;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.image_valid.VerifyCodeUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.*;

/**
 * <p>4-26 获取用户所有的课程并做题 做形考任务的！！！！！！<p>
 * <p>
 * <p>
 * <p>
 * <p>
 * 工程经济,size:1
 *
 * @author : fengx
 * @since JDK8.0
 * create by fengx on 2021/7/15 14:47
 */
public class DoLmsExamAll {



    // 完型填空类型
    public static final  String CLOZE = "subject ng-scope cloze";

    public static void main(String[] args) throws Exception {



        boolean isEngCourse = false;
        String driverPath = "d:\\ynouAutoStudy\\chromedriver.exe";
        ChromeDriver driver = Util.getDriver(driverPath);
        Thread.sleep(3000);

      //  String userName = "2221001405848";
  //      String userName = "2237001202197";
        String userName = "2115001201896";
        String pwd = "Ouchn@2021";

        isEngCourse = true;
        // 要求分数
        int requireScore = -1;

        List<String> filterCourse = Lists.newArrayList();


        boolean loop = true;


        while (loop){
            String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
            driver.get(url);
            Thread.sleep(2000);
            WebElement userNameInput = driver.findElement(By.id("loginName"));
            userNameInput.clear();
            userNameInput.sendKeys(userName);

            WebElement passwordInput = driver.findElement(By.id("password"));
            passwordInput.clear();
            passwordInput.sendKeys(pwd);

//            WebElement imgElement = driver.findElement(By.xpath("/html/body/form/div/div[1]/div/div[1]/div[1]/div/div[5]/img[1]"));
//        //    WebElement imgElement = driver.findElement(By.id("kaptchaImage"));
//            System.err.println("????????:"+imgElement.getAttribute("src"));
//            String validateCode = VerifyCodeUtils.read(imgElement.getAttribute("src"));

//            String validateCode = "";
//            WebElement imgElement = driver.findElement(By.id("kaptchaImage"));
//            Dimension dimension = imgElement.getSize();
//            Point point = imgElement.getLocation();
//            try {
//                //得到裁剪的图片
//                BufferedImage image = AnalysisIdentifyingCode.createElementImage(driver, "d://test//test2.jpg", point.x, point.y,
//                        dimension.width, dimension.height);
//                BufferedImage processedImage = AnalysisIdentifyingCode.binaryImage(AnalysisIdentifyingCode.grayImage(image));
//                //进行保存
//                ImageIO.write(processedImage, "png",  new File("d://test//test2.jpg"));
//                validateCode = VerifyCodeUtils.read("ata:image/jpg;base64,"+VerifyCodeUtils.GetImageStr("d://test//test2.jpg"));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//
//            System.err.println("validateCode:"+validateCode);
//
//            WebElement validateCodeWe = driver.findElement(By.id("validateCode"));
//            validateCodeWe.clear();
//            validateCodeWe.sendKeys(validateCode);
            Thread.sleep(10000);

            WebElement loginBtn = driver.findElement(By.name("button"));

            loginBtn.click();
            Thread.sleep(10000);

            loop = !driver.getCurrentUrl().contains("index");
        }
        //TimeUnit.SECONDS.sleep(1);

        // FIXME 要输入验证码







        Map<Long,String> courseMap = Maps.newHashMap();




        List<String> courseNames = Lists.newArrayList();
        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            System.err.println("title:" + we.findElement(By.tagName("p")).getText());
            courseNames.add(we.findElement(By.tagName("p")).getText());
        }

        courseNames.clear();
        courseNames.add("病理生理学");

        for(String courseName:courseNames){
            Util.switchToFirst(driver);
            driver.navigate().refresh();
            Thread.sleep(5000);
            for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
                if (courseName.contains(we.findElement(By.tagName("p")).getText())) {
                    we.findElement(By.tagName("a")).click();
                    Thread.sleep(1000);
                    Util.switchToLast(driver);
                    Thread.sleep(8000);
                    String cUrl = driver.getCurrentUrl();
                    String cid = cUrl.substring(cUrl.indexOf("/course/")+8,cUrl.indexOf("/ng#"));
                    courseMap.put(Long.parseLong(cid),courseName);
                    driver.close();
                    Thread.sleep(2000);
                    break;
                }
            }

        }

        System.err.println("courseMap:"+JSON.toJSONString(courseMap));



        for(Long courseId:courseMap.keySet()){
            String courseName = courseMap.get(courseId);
            if(filterCourse.contains(courseName)){
               continue;
            }
                     try {
             if(courseName.contains("英语")){
                 isEngCourse = true;
             }else {
                 isEngCourse = false;
             }
             study(driver,courseId,courseName,requireScore,isEngCourse);
         }catch (Exception e){

         }
        }






        Thread.sleep(500000000);

//
    }

    private static CourseInfo getUserCourseInfo(WebDriver driver){
        String getUrl = "https://lms.ouchn.cn/api/my-courses?conditions=%7B%22status%22:%5B%22ongoing%22%5D,%22keyword%22:%22%22%7D&fields=id,name,course_code,department(id,name),grade(id,name),klass(id,name),course_type,cover,small_cover,start_date,end_date,is_started,is_closed,academic_year_id,semester_id,credit,compulsory,second_name,display_name,created_user(id,name),org(is_enterprise_or_organization),org_id,public_scope,course_attributes(teaching_class_name,copy_status,tip,data),audit_status,audit_remark,can_withdraw_course,imported_from,allow_clone,is_instructor,is_team_teaching,academic_year(id,name),semester(id,name),instructors(id,name,email,avatar_small_url),is_master,is_child,has_synchronized,master_course(name)&page=1&page_size=10";
        String gggUrl = "https://lms.ouchn.cn/api/my-courses?conditions=%7B%22status%22:%5B%22ongoing%22%5D,%22keyword%22:%22%22%7D&fields=id,name,course_code,department(id,name),grade(id,name),klass(id,name),course_type,cover,small_cover,start_date,end_date,is_started,is_closed,academic_year_id,semester_id,credit,compulsory,second_name,display_name,created_user(id,name),org(is_enterprise_or_organization),org_id,public_scope,course_attributes(teaching_class_name,copy_status,tip,data),audit_status,audit_remark,can_withdraw_course,imported_from,allow_clone,is_instructor,is_team_teaching,academic_year(id,name),semester(id,name),instructors(id,name,email,avatar_small_url),is_master,is_child,has_synchronized,master_course(name)&page=1&page_size=10";
        String cookie = Util.getCookie(driver.manage().getCookies());
        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/user/courses");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/my-courses?conditions=%7B%22status%22:%5B%22ongoing%22%5D,%22keyword%22:%22%22%7D&fields=id,name,course_code,department(id,name),grade(id,name),klass(id,name),course_type,cover,small_cover,start_date,end_date,is_started,is_closed,academic_year_id,semester_id,credit,compulsory,second_name,display_name,created_user(id,name),org(is_enterprise_or_organization),org_id,public_scope,course_attributes(teaching_class_name,copy_status,tip,data),audit_status,audit_remark,can_withdraw_course,imported_from,allow_clone,is_instructor,is_team_teaching,academic_year(id,name),semester(id,name),instructors(id,name,email,avatar_small_url),is_master,is_child,has_synchronized,master_course(name)&page=1&page_size=10");
        heads.put("accept", "application/json, text/plain, */*");

        heads.put(":scheme","https");
        heads.put("ec-ch-ua","\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"100\", \"Google Chrome\";v=\"100\"");
        heads.put("sec-ch-ua-mobile","0");
        heads.put("sec-ch-ua-platform","\"Windows\"");
        heads.put("sec-fetch-dest","empty");
        heads.put("sec-fetch-mode","cors");
        heads.put("sec-fetch-site", "ame-origin");


        String result = null;
        try {
            result = HttpUtil.get(getUrl,cookie,heads);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.parseObject(result,CourseInfo.class);

    }

    private static void study(WebDriver driver,Long courseId,String subjectName,int requireScore,boolean isEngCourse) throws Exception {

        // 在题库里获取答案
        Map<String, AnswerObject> answerMap = null;
        try {
            answerMap = initAnswer(subjectName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, AnswerObject> originAnswers = new HashMap<>();
        for (String title : answerMap.keySet()) {
            if(isEngCourse){
                // 英语答案
                originAnswers.put(DealJsonString.removeSpace(title), answerMap.get(title));
            }else {
                // 中文
                originAnswers.put(title, answerMap.get(title));
                originAnswers.put(DealJsonString.saveZhWord(title), answerMap.get(title));
                // FIXME 除了数学，一一般情况不放开
                // originAnswers.put(dealTitleWithHref(title),answerMap.get(title));
            }
        }

        // 进入课程首页
        for (WebElement we : driver.findElements(By.cssSelector("div[class='ouchnPc_index_course_div']"))) {
            String textContent = we.getText();
            System.err.println("text:" + textContent);
            if (textContent.contains(subjectName)) {
                we.findElement(By.tagName("a")).click();
                break;
            }
        }
        Util.switchToLast(driver);


        // TODO 现在开始获取具体课程所有的答题链接：：

        List<LmsExamInfo> lmsExamInfoList = ExportLmsExamInfo.getUserCourseInfo(driver, courseId);

        List<LmsExamInfo.ExamsDTO> exams = Lists.newArrayList();
        lmsExamInfoList.forEach(e->exams.addAll(e.getExams()));


        for (LmsExamInfo.ExamsDTO examsDTO : exams) {
            String examTitle = examsDTO.getTitle();
            // 排除不计入考核的作业
            if (!Strings.isNullOrEmpty(examTitle) && examTitle.contains("不计入考核")) {
                continue;
            }
            // 排除已经做了测试的
            String score = examsDTO.getScore();
            if (!Strings.isNullOrEmpty(score) && Integer.parseInt(score) >= requireScore) {
                continue;
            }
            // 过滤掉不是形考得 FIXME
            if(!examsDTO.getTitle().contains("形考")
                    &&!examsDTO.getTitle().contains("考核")
                    &&!examsDTO.getTitle().contains("专题测验")
                    &&!examsDTO.getTitle().contains("专题检测")
                    &&!examsDTO.getTitle().contains("单元自测")
                    &&!examsDTO.getTitle().contains("30分") // FIXME
            ){
                continue;
            }

            String doExamUrl = "https://lms.ouchn.cn/course/" + courseId + "/learning-activity#/exam/" + examsDTO.getId();
            driver.get(doExamUrl);
            try {
                Thread.sleep(10 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 确认开始答题
            confirmDoAnswer(driver);

            // 找到所有的问题element
            Thread.sleep(5000);
            List<WebElement> webElements = findWeElements(driver, "li[ng-class='subject.type']", 20);
            List<WebElement> questionElements = Lists.newLinkedList();

            webElements.forEach(e -> {
                if (!e.getAttribute("class").equals("subject ng-scope text")) {
                    questionElements.add(e);
                }
            });

            // 开始答题
            doAnswer(driver, questionElements, answerMap,originAnswers);

            // 提交答题并确认提交 button button-green ng-scope
            Thread.sleep(5000);
            try {
                // right ng-scope 可以判断答题进度来决定是否提交
                String doneNums = driver.findElement(By.cssSelector("span[ng-bind='progressUi.answeredNum']")).getText();
                String allNums = driver.findElement(By.cssSelector("span[ng-bind='progressUi.subjectsNum']")).getText();
                if (Integer.parseInt(doneNums) / Integer.parseInt(allNums) < 0.90) {
                    System.err.println("完成度不够！！！！！！！！！！");
                    continue;
                }
                submitTesting(driver);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(5000);

        }
    }

    private static void confirmDoAnswer(WebDriver driver) throws InterruptedException {

        //  点击开始答题
        driver.findElement(By.cssSelector("div[class='exam-button-container ng-scope']")).findElement(By.tagName("span")).click();
        Thread.sleep(2000);
        //  for = confirm 点击勾选 我已知晓考试要求并承诺遵守考试纪律 ng-valid ng-touched ng-dirty ng-valid-parse ng-empty
        try {
            new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<WebElement>)
                    d -> Objects.requireNonNull(d).findElement(By.cssSelector("input[name='confirm']"))).click();
        } catch (Exception e) {

        }
        Thread.sleep(2000);

        for (WebElement startAnswerWe : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                d -> Objects.requireNonNull(d).findElements(By.cssSelector("button[class='button button-green medium ng-binding']")))) {
            // button button-green medium ng-binding
            if ("开始答题".equals(startAnswerWe.getText()) || "继续答题".equals(startAnswerWe.getText())) {
                startAnswerWe.click();
                break;
            }

        }
    }

    private static Map<String, AnswerObject> initAnswer(String subjectName) throws IOException {
        InputStream inputStream1 = new FileInputStream("D:\\project\\answer-tool\\src\\main\\resources\\" + subjectName + "\\" + subjectName + "-answer.json");
        String answerStr = IOUtils.toString(inputStream1, StandardCharsets.UTF_8);
        List<AnswerObject> list = JSONObject.parseArray(answerStr, AnswerObject.class);
        Map<String, AnswerObject> answerMap = Maps.newHashMap();
        for (AnswerObject answerObject : list) {
            answerMap.put(DealJsonString.delHTMLTag(Util.dealContent(answerObject.getQuestionTitle())), answerObject);
        }
        return answerMap;
    }

    private static void submitTesting(WebDriver driver) throws Exception {
        // 点击提交  交卷
        driver.findElement(By.cssSelector("a[class='button button-green ng-scope']")).click();

        // button button-green medium
        for (WebElement confirmBtn : findWeElements(driver, "button[class='button button-green medium']", 20)) {
            if ("确定".equals(confirmBtn.getText())) {
                confirmBtn.click();
                break;
            }
        }
    }


    private static void doAnswer(WebDriver driver, List<WebElement> questionWeList, Map<String, AnswerObject> answerMap,
                                 Map<String, AnswerObject> originAnswers) throws Exception {

        // fixme
        Thread.sleep(1000);
        // fixme

        System.err.println("questionWeListSize：" + questionWeList.size());


        for (WebElement questionWe : questionWeList) {
            WebElement summaryWe = questionWe.findElement(By.className("summary-title"));

            String questionType = questionWe.getAttribute("class");

            // fixme
           // WebElement titleWe = summaryWe.findElement(By.cssSelector("p[class$='ng-scope']"));
            // 如果是完型填空
//            String title = summaryWe.getText();
//            StringBuilder titleSb = new StringBuilder();
//            for(WebElement ngWe:summaryWe.findElements(By.cssSelector("*[class$='ng-scope']"))){
//                // 过滤掉题目的序号
//                if(!Strings.isNullOrEmpty(ngWe.getAttribute("ng-if"))){
//                    continue;
//                }
//                titleSb.append(ngWe.getText());
//            }
//            String title = titleSb.toString();
//            title = Util.dealContent(title);
//            title = DealJsonString.delHTMLTag(title);
            String title = Util.getLmsTitle(summaryWe,true);
            String httpTitle = dealTitleWithHref(title);
            AnswerObject answerObject = answerMap.get(title);
            if (answerObject == null) {
                answerObject = originAnswers.get(httpTitle);
            }
            if (answerObject == null) {
                answerObject = originAnswers.get(DealJsonString.removeSpace(title));
            }
            if (answerObject == null) {
                answerObject = originAnswers.get(DealJsonString.saveZhWord(title));
            }
            if (answerObject == null) {
                System.err.println("答案不存在:" + title);
                // FIXME 如果问题不存在，就用HANLP来匹配
                double similarity = 0.0;
                String answerTitle = "";
                for (Map.Entry<String, AnswerObject> entry : answerMap.entrySet()) {
                //    double k1 = DealJsonString.getSimilarity(title, entry.getKey());
                    double k1 = DealJsonString.getSimilarity(httpTitle, entry.getKey());
                    if (k1 > similarity) {
                        similarity = k1;
                        answerTitle = entry.getKey();
                    }
                }
                System.err.println("answerTitle:" + answerTitle + " similarity:" + similarity);
                // 相似度为0.9 就选择
                if (similarity > 0.60) {
                    answerObject = answerMap.get(answerTitle);
                } else {
                    try {
                        continue;
                       // Thread.sleep(20000000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            System.err.println("answerObject:" + JSONObject.toJSONString(answerObject));

//            if(title.contains("则当事件互不相容时")){
//                System.err.println("title:"+title);
//                System.err.println("deal:"+Util.getLmsTitle(questionWe.findElement(By.cssSelector("div[class='option-content']"))));
//                Thread.sleep(200000000);
//            }

            assert answerObject != null;


            switch (answerObject.getQuestionType()) {
                case "1":
                case "2":
                case "3": {
                    // 单选 多选 判断
                    doChoiceExercise(questionWe, answerObject.getAnswers());
                    break;
                }
                case "4": {
                    doGapFilling(questionWe, answerObject.getAnswers());
                    break;
                }
                case "5": {
                    doShortAnswer(questionWe, answerObject.getAnswers());
                    break;
                }
                case "6": {
                    doMultiAnswer(driver, questionWe, answerObject.getAnswers());
                    break;
                }
                case "8": {
                    doMatching(driver, questionWe, answerObject.getAnswers());
                    break;
                }
                default: {
                    throw new Exception("不支持的题型!" + questionType + answerObject.getQuestionTitle());
                }
            }
        }
    }

    private static void doMatching(WebDriver driver, WebElement answerElement, List<String> realAnswers) throws InterruptedException {

        try {
            int index = 0;

            // 所有选项
            List<WebElement> quizWeList = answerElement.findElements(By.cssSelector("div[class='clone-area drag-area ng-scope']"));

            for(WebElement we:answerElement.findElements(By.cssSelector("div[class='list-panel option ng-isolate-scope']"))){
                String realAnswer = realAnswers.get(index);

                for(WebElement quizWe:quizWeList){
                    String quizContent = quizWe.findElement(By.cssSelector("div[class='content-center']")).getText();
                    quizContent = Util.dealContent(quizContent);
                    if(!quizContent.equals(realAnswer)){
                        continue;
                    }
                    new Actions(driver).dragAndDrop(quizWe,we).perform();
                }
                index++;
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }


    /**
     * 做完型填空 下拉框|填空题类型的完形填空
     *
     * @param driver
     * @param answerElement
     * @param realAnswers
     */
    private static void doMultiAnswer(WebDriver driver, WebElement answerElement, List<String> realAnswers) throws InterruptedException{

        int index = 0;
        List<WebElement> liWeList = answerElement.findElements(By.cssSelector("li[class='sub-subject-content ng-scope']"));
        if(liWeList.size()==5){

            for (WebElement liWe:liWeList){
                for(WebElement labelWe:liWe.findElements(By.tagName("label"))){
                    WebElement contentWe = Util.findByCssSelector(labelWe,"div[class='option-content']");
                    if(contentWe==null){
                        continue;
                    }
                    if(realAnswers.get(index).equals(contentWe.getText())){
                        labelWe.click();
                        break;
                    }
                }
                index++;
            }
            return;
        }


        driver.manage().window().maximize();
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0,10000)");

        Thread.sleep(5000);

        try {

            int count = 0;
            WebElement olWe  = null;
            for (WebElement ngWe : answerElement.findElements(By.cssSelector("*[class='ng-scope']"))) {
                if(ngWe.getTagName().equals("div")){
                    continue;
                }
                WebElement selectWe = Util.findByTagName(ngWe, "select");
                if (selectWe != null) {
                    System.err.println("????ngWeeeeeeeeeeeeee"+ngWe.getText());
                    count++;
                    olWe = ngWe;
                }
            }
            System.err.println("count:"+count);

            // 如果count=1 ，说明所有的选择标签都在一个ol标签下面
            if(count == 1){

                for (WebElement ngWe : olWe.findElements(By.tagName("li"))) {

                    System.err.println("ngWe:"+ngWe.getText());

                    WebElement selectWe = Util.findByTagName(ngWe, "select");
                    if (selectWe == null) {
                        continue;
                    }

                    Thread.sleep(2000);
                    //    WebElement span =  ngWe.findElement(By.cssSelector("span[class='ui-multiselect-open']"));
                    WebElement span = ngWe.findElement(By.cssSelector("button[class^='ui-multiselect ui-widget']"));
                    Thread.sleep(2000);
                    span.click();

                    Thread.sleep(2000);

                    WebElement divWe= answerElement.findElements(By.cssSelector("div[class^='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all ui-multiselect-single multi-select']")).get(index);
                    //    new Actions(driver).contextClick(divWe).perform();;
                    //   divWe.click();
                    for(WebElement labelWe:divWe.findElements(By.tagName("label"))){
                        System.err.println("labelWe::"+labelWe.findElement(By.tagName("span")).getText());
                        if(realAnswers.get(index).equals(labelWe.getText())){
                            labelWe.click();
                            break;
                        }
                    }

                    index++;

                }
            }

            if(count == 5){
                for (WebElement ngWe : answerElement.findElements(By.cssSelector("*[class='ng-scope']"))) {

                    if(ngWe.getTagName().equals("div")){
                        continue;
                    }
                    System.err.println("ngWe:"+ngWe.getText());

                    WebElement selectWe = Util.findByTagName(ngWe, "select");
                    if (selectWe == null) {
                        continue;
                    }

                    Thread.sleep(2000);
                    //    WebElement span =  ngWe.findElement(By.cssSelector("span[class='ui-multiselect-open']"));
                    WebElement span = ngWe.findElement(By.cssSelector("button[class^='ui-multiselect ui-widget']"));
                    Thread.sleep(2000);
                    span.click();

                    Thread.sleep(2000);

                    WebElement divWe= answerElement.findElements(By.cssSelector("div[class^='ui-multiselect-menu ui-widget ui-widget-content ui-corner-all ui-multiselect-single multi-select']")).get(index);
                    //    new Actions(driver).contextClick(divWe).perform();;
                    //   divWe.click();
                    for(WebElement labelWe:divWe.findElements(By.tagName("label"))){
                        System.err.println("labelWe::"+labelWe.findElement(By.tagName("span")).getText());
                        if(realAnswers.get(index).equals(labelWe.getText())){
                            labelWe.click();
                            break;
                        }
                    }

                    index++;

                }
            }



        }catch (Exception e){
            e.printStackTrace();
        }

    }


    private static void doShortAnswer(WebElement answerElement, List<String> realAnswers) throws UnsupportedEncodingException {

        //   answerElement.findElement(By.cssSelector("div[class='subject-body short-answer']")).sendKeys(realAnswers.get(0)); 不行
        answerElement.findElement(By.cssSelector("div[class='simditor-body needsclick']")).clear();
        answerElement.findElement(By.cssSelector("div[class='simditor-body needsclick']")).sendKeys(realAnswers.get(0));

    }

    private static void doGapFilling(WebElement answerElement, List<String> realAnswers) {
        try {
            StringBuilder sb = new StringBuilder();
            realAnswers.forEach(e -> sb.append(e).append(" "));
            answerElement.findElement(By.cssSelector("var[context='subject']")).clear();
            answerElement.findElement(By.cssSelector("var[context='subject']")).sendKeys(sb.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static void doChoiceExercise(WebElement answerElement, List<String> realAnswers) {
        // 遍历题目的每一个选项
        for (WebElement singleAnswerElement : answerElement.findElements(By.cssSelector("li[class='option ng-scope vertical']"))) {

            WebElement answerWe = singleAnswerElement.findElement(By.cssSelector("div[class='option-content']"));
//            String answerContent = answerWe.getText();
//            //兼容特殊字符
//            answerContent = Util.dealContent(answerContent);
//            answerContent = DealJsonString.saveZhWord(answerContent);
//            System.err.println("answerContent:" + answerContent);
            String answerContent = Util.getLmsTitle(answerWe,false);
            // 找到单选框或复选框
            // el-checkbox el-radio
            //     WebElement labelElement = singleAnswerElement.findElement(By.cssSelector("label[ng-class='{'answered-option': option.id == subject.answeredOption}']"));
            WebElement labelElement = singleAnswerElement.findElement(By.tagName("label"));

            // 找到真正的点击按钮 el-radio__input el-checkbox__input
            WebElement realClickElement = singleAnswerElement.findElement(By.cssSelector("span[class='left']"));

            String labelClass = labelElement.getAttribute("class");
            System.err.println("labelClass:" + labelClass);

            WebElement clickWebElement = labelElement.findElement(By.tagName("input"));
            // FIXME 判断题0：对 1：错
            // 这里的ID是每个选项的ID answerContent是每个选项的内容
            for (String realAnswer : realAnswers) {
                System.err.println("origin:" + answerContent);
                // if (answerContent.equals(realAnswer)) {
              //  if (DealJsonString.delHTMLTag(answerContent).equals(DealJsonString.delHTMLTag(realAnswer))) {
                if (!Strings.isNullOrEmpty(answerContent)&&answerContent.equals(realAnswer)) {
                 //   System.err.println("realAnswer:" + realAnswer);
                    assert clickWebElement != null;
                    if (!clickWebElement.isSelected()) {
                     //   realClickElement.click();
                        clickWebElement.click();
                    }
                }
                if(realAnswer.contains("http")){
                 try {
                     System.err.println("realAnswer::::"+dealTitleWithHref(realAnswer));
                     System.err.println("singleAnswerElement::::"+dealTitleWithHref(Util.getAnswer(answerWe)));
                     if(dealTitleWithHref(realAnswer).equals(dealTitleWithHref(Util.getAnswer(answerWe)))){
                         if (!clickWebElement.isSelected()) {
                             clickWebElement.click();
                         }
                     }

                 }catch (Exception e){
                     e.printStackTrace();
                 }
                 }
            }


        }
    }




    // 明天处理一下标题

    // 处理带图片的答案；// 只剩下图片
    public static String dealTitleWithHref(String answerOrTitle){
      if(!answerOrTitle.contains("http")){
          return answerOrTitle;
      }
        String realAnswerCode = answerOrTitle.substring(0,answerOrTitle.indexOf("|[")+2);
        answerOrTitle = answerOrTitle.substring(answerOrTitle.indexOf("|[")+2,answerOrTitle.length()-1);
        System.err.println("realAnswer2222:"+answerOrTitle);
        if(answerOrTitle.contains(",")){
            for(String href:answerOrTitle.split(",")){
                realAnswerCode += JSON.toJSONString(ImageUtil.getImageFromNetByUrl(href));
            }
        }else {
            realAnswerCode += JSON.toJSONString(ImageUtil.getImageFromNetByUrl(answerOrTitle));
        }
        return  realAnswerCode;
    }


    private static List<WebElement> findWeElements(WebDriver driver, String cssSelector, int second) {
        return (new WebDriverWait(driver, Duration.ofSeconds(second))).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                });
    }


}
